package com.zhhtech.zhh.ui.helper

import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.TokenRet
import com.zhhtech.zhh.BuildConfig
import com.zhhtech.zhh.R
import com.zhhtech.zhh.api.core.FirmException
import com.zhhtech.zhh.common.AUTH_SECRET
import com.zhhtech.zhh.ui.ext.DefaultLifecycleObserver
import com.zhhtech.zhh.ui.ext.drawable
import com.zhhtech.zhh.ui.ext.toColor
import com.zhhtech.zhh.ui.utils.Logger
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class PhoneAuthHelper(private val activity: FragmentActivity) : DefaultLifecycleObserver {
    private var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null
    private var mTokenResultListener: TokenResultListener? = null
    private var checkEnvAvailableCoroutine: Continuation<Boolean>? = null
    private var getLoginTokenCoroutine: Continuation<String>? = null

    init {
        activity.lifecycle.addObserver(this)
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(tokenRet: String?) {
                kotlin.runCatching {
                    val tokenRet = TokenRet.fromJson(tokenRet)
                    when (tokenRet.code) {
                        ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS -> {
                            checkEnvAvailableCoroutine?.resume(true)
                        }
                        ResultCode.CODE_ERROR_FUNCTION_DEMOTE -> {
                            checkEnvAvailableCoroutine?.resume(false)
                        }
                        ResultCode.CODE_SUCCESS -> {
                            getLoginTokenCoroutine?.resume(tokenRet.token)
                            mPhoneNumberAuthHelper?.setAuthListener(null)
                            mPhoneNumberAuthHelper?.quitLoginPage()
                        }
                        else -> {}
                    }
                }
            }

            override fun onTokenFailed(tokenRet: String?) {
                mPhoneNumberAuthHelper?.hideLoginLoading()
                val tokenRet = TokenRet.fromJson(tokenRet)
                Logger.e("tokenRet==>$tokenRet")
                mPhoneNumberAuthHelper?.quitLoginPage()
                kotlin.runCatching {
                    when (tokenRet.code) {
                        ResultCode.CODE_ERROR_USER_CANCEL -> {
                            getLoginTokenCoroutine?.resumeWithException(FirmException())
                        }
                        else -> {
                            getLoginTokenCoroutine?.resumeWithException(FirmException(code = ResultCode.CODE_FAILED.toInt()))
                        }
                    }
                }
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(activity, mTokenResultListener).apply {
            reporter.setLoggerEnable(BuildConfig.DEBUG)
            setAuthSDKInfo(AUTH_SECRET)
            setAuthUIConfig(
                AuthUIConfig.Builder()
                    .setStatusBarColor(R.color.main_color.toColor())
                    .setNavColor(R.color.main_color.toColor())
                    .setLogBtnBackgroundDrawable(R.drawable.bg_main_radius_6.drawable)
                    .setPrivacyAlertContentBaseColor(R.color.main_color.toColor())
                    .create()
            )
            //用户控制返回键及左上角返回按钮效果
//            userControlAuthPageCancel()
            //授权页是否跟随系统深色模式
            //用户禁用utdid
            //mPhoneNumberAuthHelper.prohibitUseUtdid();
            //授权页是否跟随系统深色模式
            setAuthPageUseDayLight(true)
            //横屏水滴屏全屏适配
            //授权页物理返回键禁用
            //mPhoneNumberAuthHelper.closeAuthPageReturnBack(true);
            //横屏水滴屏全屏适配
            keepAuthPageLandscapeFullSreen(true)
        }

    }

    suspend fun checkEnvAvailable() = suspendCancellableCoroutine { coroutine ->
        checkEnvAvailableCoroutine = coroutine
        mPhoneNumberAuthHelper?.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
    }

    suspend fun getLoginToken() = suspendCancellableCoroutine { coroutine ->
        getLoginTokenCoroutine = coroutine
        mPhoneNumberAuthHelper?.getLoginToken(activity, 5000)
    }
//    fun accelerateLoginPage() {
//        mPhoneNumberAuthHelper?.accelerateLoginPage(3000, object : PreLoginResultListener {
//            override fun onTokenSuccess(s: String) {
//                Logger.e("预取号成功: $s")
//            }
//
//            override fun onTokenFailed(s: String, s1: String) {
//                Logger.e("预取号失败：, $s1")
//            }
//        })
//    }

    override fun onDestroy(owner: LifecycleOwner) {
        mPhoneNumberAuthHelper?.apply {
            removeAuthRegisterViewConfig()
            removeAuthRegisterXmlConfig()
            setAuthListener(null)
        }
        mPhoneNumberAuthHelper = null
        mTokenResultListener = null
        checkEnvAvailableCoroutine = null
        getLoginTokenCoroutine = null
    }
}